<template>
  <div class="m-2 mr-0 overflow-hidden bg-white">
    <BasicTree
title="设备类型" treeWrapperClassName="h-[calc(100%-35px)] overflow-auto" :clickRowToExpand="false"
      :treeData="treeData" :actionList="actionList" :treeHeaderAction="treeHeaderAction"
      :fieldNames="{ key: 'code', title: 'name' }" @select="handleSelect" />
    <DeviceTypeModal @register="registerTypeModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, h, createVNode } from 'vue';

import { BasicTree, TreeItem } from '@/components/Tree';
import { getDeviceTypeList, deleteDeviceType } from '@/api/collection/device'
import { TreeActionItem } from '@/components/Tree/index';
import EditOutlined from '@ant-design/icons-vue/lib/icons/EditOutlined';
import DeleteOutlined from '@ant-design/icons-vue/lib/icons/DeleteOutlined';
import DeviceTypeModal from './DeviceTypeModal.vue'
import { useModal } from '@/components/Modal/index';
import { Modal } from 'ant-design-vue';

defineOptions({ name: 'DeptTree' });

const emit = defineEmits(['select']);
const [registerTypeModal, { openModal: openDeviceTypeModal }] = useModal()
const treeData = ref<TreeItem[]>([]);

async function fetch() {
  const res = await getDeviceTypeList({})
  const formateRes = addCopyName(res)
  treeData.value = (formateRes) as unknown as TreeItem[];
}

function addCopyName(arr) {
  return arr.map(item => {
    if (item.children && item.children.length) {
      addCopyName(item.children)
    }
    item.nameCopy = item.name
    return item
  })
}

const actionList: TreeActionItem[] = [
  {
    render: (node) => {
      return h(EditOutlined, {
        class: 'ml-2',
        onClick: (e) => {
          e.stopPropagation()
          handleEdit(node)
        },
      });
    },
  },
  {
    render: (node) => {
      return h(DeleteOutlined, {
        class: 'ml-2',
        onClick: (e) => {
          e.stopPropagation()
          showConfirm(node)
        },
      });
    },
  },
];

const treeHeaderAction = () => {
  openDeviceTypeModal(true, {
    isUpdate: false,
  });
};

function handleEdit(record: Recordable) {
  console.log(record)
  openDeviceTypeModal(true, {
    record,
    isUpdate: true,
  })
}

const handleDelete = async (node) => {
  await deleteDeviceType({ id: node.id })
  fetch()
}

const showConfirm = (node) => {
  Modal.confirm({
    title: '确认删除该设备类型?',
    icon: createVNode(DeleteOutlined),
    onOk() {
      handleDelete(node);
    },
    onCancel() { },
  });
};

function handleSelect(keys) {
  console.log(keys);

  emit('select', keys[0]);
}

function handleSuccess() {
  fetch()
}

onMounted(() => {
  fetch();
});

</script>
